package ace.module.product.core.impl.manager.impl;

import ace.cmp.core.constants.CoreConstant;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.model.SaveContext;
import ace.cmp.data.spring.data.jdbc.querydsl.rsql.core.utils.SaveContextUtils;
import ace.module.common.core.impl.manager.impl.AbstractEntityOfAppManager;
import ace.module.product.api.enums.PmsCategoryTypeEnum;
import ace.module.product.api.model.dto.PmsProductCategoryRelationDto;
import ace.module.product.core.impl.dao.entity.PmsProduct;
import ace.module.product.core.impl.dao.entity.PmsProductCategoryRelation;
import ace.module.product.core.impl.dao.repository.PmsProductCategoryRelationRepository;
import ace.module.product.core.impl.manager.PmsProductCategoryRelationManager;
import java.util.Objects;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

/**
 * 商品与分类关系 spring data jdbc querydsl rsql manager implement.
 *
 * @author Caspar
 */
@Slf4j
@AllArgsConstructor
@Component
public class PmsProductCategoryRelationManagerImpl
    extends AbstractEntityOfAppManager<PmsProductCategoryRelation, Long, PmsProductCategoryRelationDto>
    implements PmsProductCategoryRelationManager {

  private final PmsProductCategoryRelationRepository pmsProductCategoryRelationRepository;

  @Override
  public SaveContext<PmsProductCategoryRelation> assemblePmsProductCategoryRelationSaveContext(PmsProduct pmsProduct, Long categoryId) {
    PmsProductCategoryRelation pmsProductCategoryRelation = this.pmsProductCategoryRelationRepository.findByPmsAppIdAndProductIdAndCategoryTypeKeyAndCategoryTypeAndDeleteFlag(
        pmsProduct.getPmsAppId(),
        pmsProduct.getId(),
        pmsProduct.getId(),
        PmsCategoryTypeEnum.DEFAULT.getCode(),
        CoreConstant.DELETE_FLAG_NOT
    );
    boolean isAdd = Objects.isNull(pmsProductCategoryRelation);
    if (isAdd) {
      pmsProductCategoryRelation = PmsProductCategoryRelation.builder()
          .id(this.getNewId())
          .pmsAppId(pmsProduct.getPmsAppId())
          .productId(pmsProduct.getId())
          .categoryId(categoryId)
          .categoryType(PmsCategoryTypeEnum.DEFAULT.getCode())
          .categoryTypeKey(pmsProduct.getId())

          .deleteFlag(CoreConstant.DELETE_FLAG_NOT)
          .createTime(System.currentTimeMillis())
          .updateTime(System.currentTimeMillis())
          .rowVersion(CoreConstant.DEFAULT_ROW_VERSION)
          .build();
    } else {
      pmsProductCategoryRelation.setCategoryId(categoryId);
    }

    return SaveContextUtils.of(pmsProductCategoryRelation, isAdd);
  }
}
